#!/usr/bin/env python

import sys

from liwe.module import LiweModule

class Links ( LiweModule ):

	def __init__ ( self, liwe ):
		super ( Links, self ).__init__ ( liwe, "links" )

		self.dbm = self.liwe.dbm

	#=================================================
	# OVERRIDDABLE METHODS
	#=================================================
	def get_manip ( self, row ):
		pass

	def list_manip ( self, row ):
		pass

	#=================================================
	# PUBLIC
	#=================================================

	def list_container ( self ):
		rs = self.dbm.select ( "contenitore_link", "*" )
		if not rs: return []
		return rs.fetchall ()

	def get_container ( self, id_cnt ):
		return self.dbm.single_row ( "contenitore_link", "*", "id = %s" % id_cnt )


	def create ( self, id_cnt, url, testo, sticky, target, id_link, active ):
		dct = {
			'id_cnt': id_cnt,
			'url': url,
			'testo': testo,
			'sticky': sticky,
			'target': target,
			'active': active
		}

		if id_link:
			self.dbm.update ( "link", dct, "id = %s" % id_link )
		else:
			self.dbm.insert ( "link", dct )
			id_link = self.dbm.insert_id ()
		

		return id_link

	def search ( self, id_cnt = None, start_point = 0, limit = 10 ):
		extras = " ORDER BY c.name, l.sticky DESC LIMIT %s,%s " % ( start_point, limit )

		tables = [ "link AS l", "contenitore_link AS c" ]
		fields = [ "c.name", "l.id", "l.id_cnt", "l.url", "l.testo", "l.sticky", "l.active", "l.target" ]
		conds = [ "l.id_cnt = c.id" ]

		if id_cnt: conds.append ( "id_cnt = %s" % id_cnt )

		conds = " AND ".join ( conds )

		tot_rows = self.dbm.count ( tables, fields, conds )

		self.dbm.debug = self.pyhp.log.error
		cur = self.dbm.select ( tables, fields, conds, extras = extras )

		rows = []

		if cur:
			for r in cur:
				self.list_manip ( r )
				rows.append ( r )

			cur.close ()

		return { "rows" : rows, "tot_rows" : tot_rows }


	def list ( self, id_cnt = None ):
		cond = []

		if id_cnt: cond.append ( "id_cnt = %s" % id_cnt )

		cond.append ( "active = 1")

		rs = self.dbm.select ( "link", "*", " AND ".join ( cond ), extras = "ORDER BY sticky DESC" )
		if not rs: return []

		return rs.fetchall ()

	def delete ( self, ids ):
		ids = ids.split ( "|" )
		str_ids = " ,".join ( ids )

		self.dbm.delete ( "link", "id IN ( %s )" % str_ids )

	def get ( self, id_link ):
		return self.dbm.single_row ( "link", "*", "id = %s" % id_link )
